package util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * @author 李东喜
 * 2009-5-23
 */
public class FileUtils extends org.apache.commons.io.FileUtils {
    
    public FileUtils() {
        super();
    }
    
    private static Logger log = Logger.getLogger(FileUtils.class);
    
    /**
     * <p>getFileSuffix("/one/two/three.suffix") = ".suffix";</p>
     * 
     * @param path
     * @return never null
     * @author 李东喜
     * 2009-8-20
     */
    public static String getFileSuffix(String path) {
        String suffix = "";
        if (null != path && !"".equals(path.trim())) {
            int index = path.lastIndexOf('.');
            if (-1 != index && path.length() != (index + 1)) {
                suffix = path.substring(index);
            }
        }
        return suffix;
    }
    
    /**
     * <p>File f = new File("D:/one/two/three.suffix");</p>
     * <p>getFileSuffix(file) = ".suffix";</p>
     * 
     * @param file
     * @return never null
     * @author 李东喜
     * 2009-8-20
     */
    public static String getFileSuffix(File file) {
        if (file.exists() && file.isFile()) {
            return FileUtils.getFileSuffix(file.getAbsolutePath());
        }
        return "";
    }
    
    
    public class TimeType {
        public static final String HOUR = "H";
        public static final String MINUTE = "M";
    }
    
    public static void getLatestFiles(String dir, String timeType, int n) {
        if (isEmpty(dir) || isEmpty(timeType) || 1 > n) {
            log.info("没有指定 [文件夹] 参数或 [时间类型] 参数或 [数量] 参数无效");
            return;
        }
        List<File> allFileList = new ArrayList<File>();
        log.info("开始获取文件...");
        getAllFiles(new File(dir), allFileList);
        log.info(String.format("文件夹 [%1$s] \n有 [%2$s] 个文件", dir, allFileList.size()));
        log.info("开始 Copy 文件...");
        for (File file : allFileList) {
            if (isFileMatched(file, timeType, n)) {
                try {
                    copyFile(dir, file);
                } catch (IOException e) {
                    log.info(String.format("发生异常 Copying file: [%1$s]", file.getAbsolutePath()));
                    e.printStackTrace();
                }
            }
        }
        log.info("Copy 结束");
        allFileList = null;
        System.gc();
    }
    
    public static void getAllFiles(File dir, List<File> fileList) {
        if (!dir.exists() || !dir.isDirectory()) {
            log.info(String.format("文件夹不存在或不是文件夹：[%1$s]", dir.getAbsolutePath()));
            return;
        }
        File[] fa = dir.listFiles();
        log.info(String.format("文件夹：[%1$s] 的文件数：[%2$s]", dir.getAbsoluteFile(), fa.length));
        for (File file : fa) {
            if (file.isFile()) {
                fileList.add(file);
            } else if (file.isDirectory()) {
                getAllFiles(file, fileList);
            }
        }
        fa = null;
        System.gc();
    }
    
    public static boolean isFileMatched(File f, String timeType, int n) {
        
        long lt = f.lastModified();
        long st = System.currentTimeMillis();
        // hour
        int t = 1000 * 60 * 60;
        if (TimeType.MINUTE.equalsIgnoreCase(timeType)) {
            // minute
            t = 1000 * 60;
        }
        int i = (int) Math.ceil((st - lt) * 1.0 / t);
        if (i < n) {
            return true;
        }
        
        return false;
    }
    
    public static void copyFile(String dir, File sf) throws IOException {
        
        InputStream is = null;
        OutputStream os = null;
        
        File f = new File(dir);
        
        try {
            File df = new File("matchedFiles/" + f.getName() + sf.getAbsolutePath().substring(dir.length()));
            File pdf = df.getParentFile();
            if (!pdf.exists()) {
                pdf.mkdirs();
            }
            if (!df.exists()) {
                df.createNewFile();
            }
            is = new FileInputStream(sf);
            os = new FileOutputStream(df);
            IOUtils.copy(is, os);
            log.info(String.format("文件: [%1$s]\n\tCopied to: [%2$s]", sf.getAbsolutePath(), df.getAbsolutePath()));
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            IOUtils.close(is);
            IOUtils.close(os);
        }
    }
    
    public static boolean isEmpty(String s) {
        return null == s || "".equals(s.trim());
    }
    
    public static boolean isNotEmpty(String s) {
        return isEmpty(s);
    }
    
    /**
     * 解析xml文件
     * @param path
     * @return
     * @author 李东喜
     * 2009-7-27
     */
    public static List<Map<String, String>> parseXml(String path, String arg1, String arg2) {
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException(String.format("xml文件不存在：[%1$s]", file.getAbsolutePath()));
        }
        return parseXml(file, arg1, arg2);
    }
    
    /**
     * 解析xml文件
     * @param path
     * @return
     * @author 李东喜
     * 2009-7-27
     */
    public static List<Map<String, String>> parseXml(File file, String arg1, String arg2) {
        List<Map<String, String>> l = new ArrayList<Map<String,String>>();
        
        try {
            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
            DocumentBuilder b = f.newDocumentBuilder();
            Document doc = b.parse(file);
            doc.normalize();
            
            Element root = doc.getDocumentElement();
            NodeList nodeList = root.getElementsByTagName(arg1);
            String[] args = arg2.replaceAll("\\s", "").split(",");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element e = (Element) nodeList.item(i);
                for (String arg : args) {
                    log.info(e.getElementsByTagName(arg).item(0).getNodeValue());
                }
            }
            
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return l;
    }
    
    public static void zip(Map<String, byte[]> map, OutputStream os) throws IOException {
        zip(map, new ZipOutputStream(os));
    }
    
    public static Map<String, byte[]> unZip(InputStream is) throws IOException {
        return unZip(new ZipInputStream(is));
    }
    
    public static void zip(Map<String, byte[]> map, ZipOutputStream zos) throws IOException {
        for (Entry<String, byte[]> entry : map.entrySet()) {
            zos.putNextEntry(new ZipEntry(entry.getKey()));
            zos.write(entry.getValue());
        }
        zos.flush();
    }
    
    public static Map<String, byte[]> unZip(ZipInputStream zis) throws IOException {
        Map<String, byte[]> map = new HashMap<String, byte[]>(0);
        ZipEntry entry = null;
        while (null != (entry = zis.getNextEntry())) {
            System.out.println(entry.getName());
            if (!entry.isDirectory()) {
                map.put(entry.getName(), IOUtils.toByteArray(zis));
            }
            zis.closeEntry();
        }
        return map;
    }
    
    public static void handle() {
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(new FileInputStream("D:\\20090911153809047592.zip"));
            Map<String, byte[]> map = unZip(zis);
            Set<Entry<String, byte[]>> entries = map.entrySet();
            for (Entry<String, byte[]> entry : entries) {
                String name = entry.getKey();
                if (name.endsWith("doc.xml")) {
                    String prefix = name.substring(0, name.indexOf('\\'));
                    Properties p = new Properties();
                    p.loadFromXML(new ByteArrayInputStream(entry.getValue()));
                    String htmlImages = p.getProperty("html.images");
                    for (Entry<Object, Object> _entry : p.entrySet()) {
                        System.out.println(_entry.getKey());
                        System.out.println(_entry.getValue());
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    public static void main(String[] args) {
        handle();
    }
    
}
